<template>
  <div class="box">
    <my-header @userLogin="userLogin" @setUserName="setUserName" />
    <div class="content">
      <!-- 图片容器 -->
      <div class="img_box" v-if="isLogin">
        <VueCropper
          class="img"
          :img="currentImg"
          :canMove=true
          ref="cropper">
        </VueCropper>
      </div>

      <div class="default_img_box" v-else>
        <img class="default_img" :src="defaultImg" alt="">
      </div>

      <!-- 加载器 -->
      <loading 
        :active.sync="isLoading" 
        class="loading"
        :can-cancel="true" 
        color="#409eff"
        loader="dots"
      />

      <!-- 选项按钮 -->
      <div class="btns">
        <div class="btn_box">
          <el-radio class="btn youxiu" v-model="radio" label="1" size="large" border>优秀</el-radio>
        </div>
        <div class="btn_box">
          <el-radio class="btn yiban" v-model="radio" label="2" size="large" border>一般</el-radio>
        </div>
        <div class="btn_box">
          <el-radio class="btn paichu" v-model="radio" label="3" size="large" border>排除</el-radio>
        </div>
      </div>

      <!-- 提交 -->
      <el-button type="primary" size="large" @click="nextImg">下一个</el-button>
    </div>
  </div>
</template>

<script>
  import myHeader from 'components/Header.vue'
  import { VueCropper } from 'vue-cropper'
  import { ElMessage } from 'element-plus'
  import Loading from 'vue-loading-overlay'

  export default {
    name: 'Home',
    components: {
      myHeader,
      VueCropper,
      Loading
    },
    data() {
      return {
        isLogin: false,       // 判断当前用户是否登录（通过子组件传递 true）

        radio: "",
        defaultImg: require('../assets/default-img.svg'),
        currentImg: '',
        isLoading: false,     // 控制加载动画的显示与隐藏

        username: '',         // 用于登录后返回当前用户没有评判过的图片

        imgInfo: {
          _id: '',
          filename: '',
          pagecode: '',
          num: -1,
          display_count: 0,
          rates: {
            openid: '',
            nickname: '',
            headimgurl: '',
            result: ''
          }
        },

        userInfo: {
          openid: window.sessionStorage.openid,
          username: window.sessionStorage.username,
          headimgurl: window.sessionStorage.headimgurl
        }
      }
    },
    watch: {
      // 监听 radio 的改变
      'radio': function() {
        this.imgInfo.result = this.radio
      },

      // 处理 加载 loading 动画
      'currentImg': function() {
        if (this.currentImg) {
          this.isLoading = false 
        } else {
          this.isLoading = true
          this.radio = ''
        }
      },

      'isLogin': function() {
        let username = window.sessionStorage.username
        // 确定已经登陆 并且 有 username
        this.isLogin && username ? this.getImg() : console.log('当前 userinfo 为空');;
        this.isLogin ? console.log('用户已登陆') : ElMessage.info('注销成功！');
      },

      'imgInfo': function() {
        // 当图片显示时，图片数据库字段的 display_count ++
        this.imgInfo.display_count++

        console.log('当前图片信息：');
        console.log(this.imgInfo);

        let changeCount = {
          display_count: this.imgInfo.display_count,
          pagecode: this.imgInfo.pagecode
        }

        // 图片渲染时发送请求 修改图片的显示次数 display_count
        this.axios.patch(`http://wuwei.dayaar.com.cn:5432/${ this.imgInfo.num }/${ window.sessionStorage.username }`, changeCount)

        // 在 url 中添加参数
        this.$router.push({path: '/', query: { num: this.imgInfo.num, username: window.sessionStorage.username }})
      }
    },
    methods: {
      // 处理子组件传递的 参数
      userLogin(val) {
        this.isLogin = val.login
        this.username = val.username
        console.log('this.isLogin : ' + this.isLogin);
      },

      // 处理子组件传递的 参数
      setUserName(val) {
        this.username = val.username
        console.log('this.username : ' + this.username);
      },

      // 显示后端响应的图片
       async getImg() {
        try {
          const res = await this.axios.get(`http://wuwei.dayaar.com.cn:5432/getImg/${this.imgInfo.num}/${window.sessionStorage.username}`) 
          this.currentImg = 'http://www.dayaar.com.cn/evaluation-platform' + res.data.filename,
          this.imgInfo = res.data  
        } catch(err) {
          console.log(err);
        }
      },

      // 下一个
      async nextImg() {
        try {
          // 判断用户是否勾选分类
          if (!this.radio) {
            ElMessage.error('请选择分类')
            return
          } 

          // 判断用户是否登录
          if (!window.sessionStorage.openid) {
            ElMessage.error('请登录后操作')
            return
          }

          // 向后端传递用户提交结果
          const params = {
            openid: window.sessionStorage.openid,
            username: window.sessionStorage.username,
            headimgurl: window.sessionStorage.headimgurl,
            result: this.radio
          }

          // 存储修改后的图片数据
          this.axios.patch(`http://wuwei.dayaar.com.cn:5432/${this.imgInfo.num}/${window.sessionStorage.username}`, params)

          // 获取 router.patch('/:num', (req, res) => {....}) 返回的 res 数据
          .then(res => {
            console.log(res.data);
            this.currentImg = 'http://www.dayaar.com.cn/evaluation-platform' + res.data.filename,
            this.imgInfo = res.data
          })

          ElMessage.success('提交成功！！！')
          this.currentImg = ''
          
        } catch(err) {
          console.log(err);
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  .box {
    width: 100%;
    height: 100%;
    
    .content {
      width: 100%;
      height: 85vh;
      // margin-top: 40px;
      background-color: #eee;
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 20px 30px;

      .loading {
        position: absolute;
        left: -300px;
      }
      .img_box {
        width: 70%;
        height: 90%;
        background-color: #fff;
        .img { 
          width: 100%;
          height: 100%;
        }
      }
      .default_img_box {
        width: 70%;
        height: 90%;
        background-color: #fff;
        position: relative;
        .default_img {
          width: 50%;
          height: 50%;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
      .btns {
        widows: 100px;
        height: 300px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .btn_box {
          width: 100px;
          height: 50px;
          margin-bottom: 30px;
          display: flex;
          justify-content: space-around;
          align-items: center;
          .btn {
            width: 100%;
            height: 100%;
          }
          .youxiu {
            background-color: #00ff00;
          }
          .yiban {
            background-color: orange;
          }
          .paichu {
            background-color: #f56c6c;
          }
        }
      }
    }
  }
</style>